//
//  InstallationSignatureService.swift
//  ezyform
//
//  Created by Moennig Q on 21/4/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import Foundation
import CoreLocation
import AVFoundation
import HandyJSON
class InstallationSignatureService {
    
    weak var currentVC: BaseViewController!
//    open class func shared() -> InstallationSignatureService{
//        struct Static {
//            static let instance : InstallationSignatureService = InstallationSignatureService()
//        }
//        return Static.instance
//    }
    func setDataInfo(_ vc: BaseViewController, param: [String: Any] = [:])->Self{
        self.currentVC = vc
        return self
    }
    func backToDetailVC(){
        if let vc = self.currentVC, let detailVC = InstallationDetailVCHelper.shared.getJobDetaiVC(vc.navigationController){
            InstallationDetailVCHelper.shared.cacheData()//缓存新数据，刷新detail界面的数据
            self.currentVC.navigationController?.popToViewController(detailVC, animated: true)
        }
    }
    //MARK: - 检查是否需要重签
    func checkIfNeedResign(_ type: SignatureType)->Bool{
        var resignFlag: Bool = false
        switch type {
        case .InstallerAndDesiger:
            if JobDetailModelHelper.shared.jobDetailModel.signatures.installer_signed_signature != "" && JobDetailModelHelper.shared.jobDetailModel.signatures.designer_signed_signature != ""{
                resignFlag = true
            }
        case .Installer:
            if JobDetailModelHelper.shared.jobDetailModel.signatures.installer_signed_signature != "" {
                resignFlag = true
            }
        case .Designer:
            if JobDetailModelHelper.shared.jobDetailModel.signatures.designer_signed_signature != "" {
                resignFlag = true
            }
        case .Owner:
            if JobDetailModelHelper.shared.jobDetailModel.signatures.owner_signed_signature != "" {
                resignFlag = true
            }
        case .Witness:
            if JobDetailModelHelper.shared.jobDetailModel.signatures.witness_signed_signature != "" {
                resignFlag = true
            }
        default:
            break
        }
        return resignFlag
    }
    func toSignature(_ type: SignatureType){
        APPConfig.loginInfo.signatureInfoModel = SignatureInfoModel()
        switch type {
        case .Installer, .InstallerAndDesiger:
            self.checkIfIsNewFormWhenSign {
                var checkMsg: String = ""
                if type == .InstallerAndDesiger {//InstallerAndDesiger,要同时检查installer和designer必填项
                    checkMsg = InstallationDetailVCHelper.shared.checkReqiredInfoWhenInstallerAndDesignerSign()
                }else{//installer
                    checkMsg = InstallationDetailVCHelper.shared.checkReqiredInfoWhenInstallerSign()//必填字段有空值
                }
                if checkMsg != "" {
                    Tool().showAlertViewWithOneBtn(message: checkMsg)
                }else{
                    self.toInstallerSign(type)
                }
            } oldClosure: {
                self.toInstallerSign(type)
            }
        case .Owner:
            self.checkIfIsNewFormWhenSign {
                let checkMsg = InstallationDetailVCHelper.shared.checkReqiredInfoWhenOwnerSign()//必填字段有空值
                if checkMsg != "" {
                    Tool().showAlertViewWithOneBtn(message: checkMsg)
                }else{
                    APPConfig.loginInfo.currentSignatureType = .Owner
                    self.toOwnerSignVC(true)
                }
            } oldClosure: {
                self.toOwnerSignVC(false)
            }
        case .Designer:
            self.checkIfIsNewFormWhenSign {
                let checkMsg = InstallationDetailVCHelper.shared.checkReqiredInfoWhenDesignerSign()//必填字段有空值
                if checkMsg != "" {
                    Tool().showAlertViewWithOneBtn(message: checkMsg)
                }else{
                    APPConfig.loginInfo.currentSignatureType = .Designer
                    self.toStatementVC(.Designer)
                }
            } oldClosure: {
                self.toSignatureVC(.Designer)
            }
        case .Witness:
            self.checkIfIsNewFormWhenSign {
                let checkMsg = InstallationDetailVCHelper.shared.checkReqiredInfoWhenWitnessSign()//必填字段有空值
                if checkMsg != "" {
                    Tool().showAlertViewWithOneBtn(message: checkMsg)
                }else{
                    self.toSignatureVC(.Witness)
                }
            } oldClosure: {
                self.toSignatureVC(.Witness)
            }
        default:
            break
        }
    }
    fileprivate func toInstallerSign(_ type: SignatureType){
        self.checkLocationService()
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (status) in
            DispatchQueue.main.sync {
                if status {
                    APPConfig.loginInfo.currentSignatureType = type
                    if JobDetailModelHelper.shared.jobDetailModel.solar_water_heater && type == .Installer {//热水器的installer没有协议，但是签名需要自拍照
                        let vc = InstallerSignForNewStcFormVC()
                        self.currentVC.navigationController?.pushViewController(vc, animated: false)
                    }else{
                        self.toStatementVC(.Installer)
                    }
                }else{
                    Tool().showAlertViewWithOneBtn(message: NSLocalizedString("camera.permission", comment: ""))
                }
            }
        }
        
    }
    //跳转到协议界面，用户新协议或老协议
    private func toStatementVC(_ statementType: SignatureType) {
        let vc = OnlineStatementViewController(statementType: statementType,  clearWebiewCacheFlag: true)
        self.currentVC.navigationController?.pushViewController(vc, animated: false)
    }
    
    func checkIfIsNewFormWhenSign(_ newClosure:(()->Void)?, oldClosure: (()->Void)?){
        let loadingText = (Connectivity.isConnectedToInternet ? "Loading..." : "")
        InstallationDetailVCHelper.shared.cacheJobDetail(loadingText,successClosure: {
            //先获取最新的pvd detail数据，因为Designer statement中有引用相关信息
            if JobDetailModelHelper.shared.jobDetailModel.job_status == PVDJobStatusValue.installed.rawValue {//installed ： 如果job finished了，先刷新detial信息，再提示reopen后重签
                Tool().showAlertViewWithOneBtn(message: "The job has been finished, if you want to re-sign please reopen the job.")
            }else{//installing ,unqualified才能签名
                if JobDetailModelHelper.shared.jobDetailModel.is_new_stc_form{//isNewStcForm=true表示是2022-04-01之后创建的job，需要联网签名且签名签retailer 已经签名
                    if Connectivity.isConnectedToInternet {//联网签名
                        newClosure?()
                    }else{//无网络要提示必须联网签名
                        Tool().showAlertViewWithOneBtn(message: "Signing off on the statement will require an internet connection. This is to ensure the information on the statement is up to date in real time.")
                    }
                }else{//2022-04-01之前创建的job
                    oldClosure?()
                }
            }
        },faildClosure: {(code, err) in
            Tool().showErrorInfo(code,err)//处理离线点击签名时，给与相应错误提示
        })
    }
    fileprivate func toSignatureVC(_ type: SignatureType){
        let vc = PVDSignagtureViewController()
        vc.signatureType = type
        self.currentVC.navigationController?.pushViewController(vc, animated: false)
    }
    
    func toOwnerSignVC(_ newStcFormFlag: Bool = false){
        if self.checkIfNeedResign(.Owner) {//owner如果是重签，只能在app签，不能发送sms或email了
            AVCaptureDevice.requestAccess(for: AVMediaType.video) { (status) in
                DispatchQueue.main.sync {
                    if status {
                        APPConfig.loginInfo.currentSignatureType = .Owner
                        self.toStatementVC(.Owner)
                    }else{
                        Tool().showAlertViewWithOneBtn(message: NSLocalizedString("camera.permission", comment: ""))
                    }
                }
            }
        }else{
            let cellList = [CellModel(title: R.string.localizable.signInAPP(), imageName: "installation_detail_sigauture_sign_in_app"),
                            CellModel(title: R.string.localizable.sendBySMS(), imageName: "installation_detail_sigauture_sign_send_sms"),
                            CellModel(title: R.string.localizable.sendByEmail(), imageName: "installation_detail_sigauture_sign_send_email")]
            
            let actionSheetView = CustomActionSheet(title: R.string.localizable.pleaseSelectASignatureMode(), aCellArray: cellList, aCancelModel: CellModel(title: R.string.localizable.cancel(), imageName: ""), aSelectedClosure: { (row) in
                if row == 0 {//sign in app
                    AVCaptureDevice.requestAccess(for: AVMediaType.video) { (status) in
                        DispatchQueue.main.sync {
                            if status {
                                APPConfig.loginInfo.currentSignatureType = .Owner
                                self.toStatementVC(.Owner)
                            }else{
                                Tool().showAlertViewWithOneBtn(message: NSLocalizedString("camera.permission", comment: ""))
                            }
                        }
                    }
                }else if row == 1{//send sms
                    let vc = SendSMSToOwnerViewController()
                    self.currentVC.navigationController?.pushViewController(vc, animated: false)
                }else if row == 2 {//send email
                    let vc = SendEmailToOwnerViewController()
                    self.currentVC.navigationController?.pushViewController(vc, animated: false)
                }
            }, aCancelClosure: nil)
            self.currentVC.navigationController?.view.addSubview(actionSheetView)
        }
    }
    fileprivate func checkLocationService(){
        let status  = CLLocationManager.authorizationStatus()
        if status == .denied || status == .restricted {
            Tool().showAlertViewWithTwoBtns(title: R.string.localizable.locationServicesHaveToBeEnabledWhenUsingTheApp(),message: R.string.localizable.turnOnLocationServicesToVerifyRequiredOnsiteDataEgPanelsSerialNumbers(), cancelStr: R.string.localizable.cancel(), confirmStr: R.string.localizable.settings(),noClosure: nil) {
                if  UIApplication.shared.canOpenURL(URL(string: UIApplication.openSettingsURLString)!) {
                    UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
                }
            }
        }
    }
    //MARK: - 2022-04-01之后或之前安装的Job都用此方法上传，用于is_new_stc_form = true, 只能在线签名，不需要离线功能
    //      - 备注：2022-04-01之后的job只能在线签名，不需要离线功能； 2022-04-01之前的job有离线功能
    func requestUploadSignature(succussClosure: @escaping (()->Void),faildClosure: @escaping ((String,String)->Void)){
        let signaturesVM = JobDetailService()
        signaturesVM.setBlockAfterNetwork({ (result , _) -> Void in
            ModelViewUtil.shared.hideLoadingView()
            //
            if let resultStr = result as? String, let newSignature = JSONDeserializer<InstallationDetailSignatures>.deserializeFrom(json: resultStr){
                //installer
                let signatureInfo = JobDetailModelHelper.shared.jobDetailModel.signatures
                signatureInfo.installer_full_name = newSignature.installer_full_name
                signatureInfo.installer_signed_at = newSignature.installer_signed_at
                signatureInfo.installer_signed_signature = newSignature.installer_signed_signature
                //designer
                signatureInfo.designer_full_name = newSignature.designer_full_name
                signatureInfo.designer_signed_at = newSignature.designer_signed_at
                signatureInfo.designer_signed_signature = newSignature.designer_signed_signature
                //owner
                signatureInfo.owner_full_name = newSignature.owner_full_name
                signatureInfo.owner_signed_at = newSignature.owner_signed_at
                signatureInfo.owner_signed_signature = newSignature.owner_signed_signature
                //witness
                signatureInfo.witness_signed_name = newSignature.witness_signed_name
                signatureInfo.witness_signed_at = newSignature.witness_signed_at
                signatureInfo.witness_signed_signature = newSignature.witness_signed_signature
                //
                JobDetailModelHelper.shared.jobDetailModel.signatures = signatureInfo
                succussClosure()
            }
        }) { (code, error) -> Void in
            ModelViewUtil.shared.hideLoadingView()
            faildClosure(code,error)
        }
        ModelViewUtil.shared.showLoadingView(R.string.localizable.uploading())
        signaturesVM.uploadSignaturesForNewStcForm(APPConfig.loginInfo.signatureInfoModel)
    }
    //最后一步：Owner保存签名时，job从4月一号签改成4月以后之后，如果签了相应的签名，要删除相应的本地签名数据
    func dealLocalSignatureByOwnerSave(){
        switch APPConfig.loginInfo.currentSignatureType {
        case .Installer://删除Installer和Owner，witness签名
            self.deleteLocalSignatures([.Installer,.Owner,.Witness])
        case .Designer://删除Designer和Owner，witness签名
            self.deleteLocalSignatures([.Designer,.Owner,.Witness])
        case .InstallerAndDesiger://删除Designer，installer和Owner，witness签名
            self.deleteLocalSignatures([.Installer,.Designer,.Owner,.Witness])
        case .Owner://删除Owner，witness签名
            self.deleteLocalSignatures([.Owner,.Witness])
        default:
            break
        }
    }
    //MARK: - 1.老协议签名上传后删除本地数据最后一步：
    //        2.新协议Witness保存签名时，如果job安装日期从4月一号签改成4月以后之后，也就是使用信息以，如果签了相应的签名，要删除相应的本地签名数据
    func dealLocalSignatureByWitnessSave(){
        switch APPConfig.loginInfo.currentSignatureType {
        case .Installer://删除Installer和Owner，witness签名
            self.deleteLocalSignatures([.Installer])
        case .Designer://删除Designer和Owner，witness签名
            self.deleteLocalSignatures([.Designer])
        case .InstallerAndDesiger://删除Designer，installer和Owner，witness签名
            self.deleteLocalSignatures([.Installer,.Designer])
        case .Owner://删除Owner，witness签名
            if JobDetailModelHelper.shared.jobDetailModel.is_new_stc_form {//新job
                self.deleteLocalSignatures([.Owner,.Witness])
            }else{//老job只删除owner
                self.deleteLocalSignatures([.Owner])
            }
        case .Witness://witness签名
            self.deleteLocalSignatures([.Witness])
        default:
            break
        }
    }
    //
    fileprivate func deleteLocalSignatures(_ signTypes:[SignatureType]){
        //Installer
        if signTypes.contains(.Installer){
            
            DBManager.shared.deleteSignatueDataBySignType(JobDetailModelHelper.shared.jobDetailModel.id, signatueType: SignatureType.Installer)
        }
        //designer
        if signTypes.contains(.Designer){
            DBManager.shared.deleteSignatueDataBySignType(JobDetailModelHelper.shared.jobDetailModel.id, signatueType: .Designer)
        }
        //owner
        if signTypes.contains(.Owner){
            DBManager.shared.deleteSignatueDataBySignType(JobDetailModelHelper.shared.jobDetailModel.id, signatueType: SignatureType.Owner)
        }
        //witness
        if signTypes.contains(.Witness){
            DBManager.shared.deleteSignatueDataBySignType(JobDetailModelHelper.shared.jobDetailModel.id, signatueType: SignatureType.Witness)
        }
    }
    deinit{
        DebugLog("InstallationSignatureService deinit")
    }
}
